<template>
  <div class="content-wrapper" v-loading="loading">
    <div class="nav">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/administration-attendanceList' }">人事档案</el-breadcrumb-item>
        <el-breadcrumb-item>考勤列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content">
      <div class="search-bar">
        <div>
          <el-input placeholder="按照名字模糊查询" prefix-icon="el-icon-search" v-model="searchData.name" style="width: 180px; margin-right: 10px;" @change="getAttendanceList"></el-input>
          <el-button type="primary" @click="showDialog(false)" v-if="isAuth('archives:attendance:save') && lastMonth === searchData.month">新增</el-button>
          <el-button type="primary" :disabled="multipleSelection.length === 0" @click="delAttendance(true)" v-if="isAuth('archives:attendance:delete') && lastMonth === searchData.month">批量删除</el-button>
          <el-button type="primary" @click="importList" v-if="isAuth('archives:attendance:save') && lastMonth === searchData.month">导入</el-button>
          <input ref="uploadInput" type="file" style="display: none;" @change="uploadFile($event)">
          <el-button type="primary" @click="exportList" v-if="isAuth('archives:attendance:list') && isAuth('archives:attendance:info')">导出</el-button>
        </div>
        <el-date-picker
          style="width: 150px;"
          v-model="searchData.month"
          type="month"
          placeholder="选择月"
          value-format="yyyy-MM"
          @change="getAttendanceList">
        </el-date-picker>
      </div>
      <div class="main-content">
        <el-table
          :data="attendanceList"
          :height="tableHeight+'px'"
          border
           @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
          <el-table-column prop="attendanceUserName" sortable label="姓名" min-width="100" align="center"></el-table-column>
          <el-table-column prop="attendanceGroup" sortable label="考勤组" min-width="200" align="center"></el-table-column>
          <el-table-column prop="attendanceDeptName" sortable label="部门" min-width="200" align="center"></el-table-column>
          <el-table-column prop="attendanceUserJobnumber" sortable label="工号" min-width="120" align="center"></el-table-column>
          <el-table-column prop="attendanceTheoretical" sortable label="应出勤天数" min-width="120" align="center"></el-table-column>
          <el-table-column prop="attendanceActual" sortable label="实际出勤天数" min-width="130" align="center"></el-table-column>
          <el-table-column prop="attendanceDayOff" sortable min-width="120" align="center">
            <template slot="header" slot-scope="scope">
              <el-tooltip effect="dark" content="病假已打折" placement="bottom">
                <span>请假天数<i class="el-icon-info"></i></span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="attendanceDayoffNumber" sortable label="请假次数" min-width="120" align="center"></el-table-column>
          <el-table-column prop="attendanceLateNumber" sortable label="迟到次数" min-width="120" align="center"></el-table-column>
          <el-table-column prop="attendanceLateDuration" sortable label="迟到时长(分钟)" min-width="140" align="center"></el-table-column>
          <el-table-column prop="attendanceOvertimeDuration" sortable label="加班时长(小时)" min-width="140" align="center"></el-table-column>
          <el-table-column label="操作" min-width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" style="padding: 0;" @click="showDialog(scope.row)" v-if="isAuth('archives:attendance:update') && lastMonth === searchData.month">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageConfig.pageIndex"
            :page-sizes="[10, 15, 20, 50, 100, 500]"
            :page-size="pageConfig.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageConfig.totalCount">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :title="(!form.id ? '新增' : '编辑') + '考勤记录'"
       :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form ref="form" :rules="dataRule" :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="attendanceUserName" :rules="[{ required: true, message: '请选择员工', trigger: 'blur' }]">
              <el-input v-model="form.attendanceUserName" disabled><el-button slot="append" @click="selectDingUsers('attendanceDingId', 'attendanceUserName', 1)">选择</el-button></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考勤组" prop="attendanceGroup" :rules="[{ required: true, message: '请输入考勤组', trigger: 'blur' }]">
              <el-input v-model="form.attendanceGroup"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门">
              <el-popover
                ref="menuListPopover"
                placement="bottom-start"
                trigger="click">
                <el-tree
                  :data="departmentList"
                  :props="{ label: 'name', children: 'children' }"
                  node-key="id"
                  ref="tree"
                  @current-change="menuListTreeCurrentChangeHandle"
                  :default-expand-all="true"
                  :highlight-current="true"
                  :expand-on-click-node="false">
                </el-tree>
              </el-popover>
              <el-input v-model="form.attendanceDeptName" v-popover:menuListPopover disabled>
                <el-button slot="append">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户工号">
              <el-input v-model="form.attendanceUserJobnumber"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="应出勤天数" prop="attendanceTheoretical"
            :rules="[{ required: true, message: '请输入应出勤天数', trigger: 'blur' }]">
              <el-input v-model="form.attendanceTheoretical" type="number" step="1" min="0" @wheel.native.prevent="stopScrollFun($event)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际出勤天数">
              <el-input v-model="attendanceActual" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="请假天数" prop="attendanceDayOff"
            :rules="[{ required: true, message: '请输入请假天数', trigger: 'blur' }]">
              <el-input v-model="form.attendanceDayOff" type="number" step="1" min="0" @wheel.native.prevent="stopScrollFun($event)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假次数" prop="attendanceDayoffNumber">
              <el-input v-model="form.attendanceDayoffNumber" type="number" step="1" min="0" @wheel.native.prevent="stopScrollFun($event)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="迟到次数" prop="attendanceLateNumber">
              <el-input v-model="form.attendanceLateNumber" type="number" step="1" min="0" @wheel.native.prevent="stopScrollFun($event)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="迟到时长" prop="attendanceLateDuration"
            :rules="[{ required: true, message: '请输入迟到时长', trigger: 'blur' }]">
              <el-input v-model="form.attendanceLateDuration" type="number" min="0" @wheel.native.prevent="stopScrollFun($event)"><template slot="append">分钟</template></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="加班时长" prop="attendanceOvertimeDuration"
            :rules="[{ required: true, message: '请输入加班时长', trigger: 'blur' }]">
              <el-input v-model="form.attendanceOvertimeDuration" type="number" min="0" @wheel.native.prevent="stopScrollFun($event)"><template slot="append">小时</template></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" style="display: flex; justify-content: space-between;">
        <div><el-button @click="delAttendance(false)" size="mini" type="danger" v-if="form.id && isAuth('archives:attendance:delete')">删除</el-button></div>
        <div>
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" size="mini">确定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import { treeDataTranslate } from '@/utils'
export default {
  data () {
    var positiveInteger = (rule, value, callback) => {
      const boolean = new RegExp('^[1-9][0-9]*$').test(value) || value === '0'
      if (!boolean) {
　　    callback(new Error('请输入非负整数'))
　　  } else {
        callback()
      }
    }
    return {
      tableHeight: '',
      searchData: {
        name: '',
        month: ''
      },
      pageConfig: {
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0,
      },
      attendanceList: [],
      dialogVisible: false,
      form: {
        attendanceDingId: '',
        attendanceUserName: '',
        attendanceGroup: '',
        attendanceDeptId: '',
        attendanceDeptName: '',
        attendanceUserJobnumber: '',
        attendanceTheoretical: '',
        attendanceActual: '',
        attendanceDayOff: '',
        attendanceDayoffNumber: '',
        attendanceLateNumber: '',
        attendanceLateDuration: '',
        attendanceOvertimeDuration: '',
        attendanceStatisticsDuration: ''
      },
      departmentList: [],
      curMonth: '',
      lastMonth: '',
      loading: false,
      multipleSelection: [],
      dataRule: {
        attendanceDayoffNumber: [
          { required: true, message: '请输入请假次数', trigger: 'blur' },
          { validator: positiveInteger, trigger: 'blur' },
        ],
        attendanceLateNumber: [
          { required: true, message: '请输入迟到次数', trigger: 'blur' },
          { validator: positiveInteger, trigger: 'blur' },
        ],
      }
    };
  },
  components: {},
  mixins: [dingMixin],
  computed: {
    attendanceActual() {
      return Number(this.form.attendanceTheoretical) - Number(this.form.attendanceDayOff)
    }
  },
  mounted () {
    this.tableHeight = document.documentElement['clientHeight'] - 170
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 170
    }
    this.getCurMonth()
    this.getAttendanceList(true)
    this.getAllDeptList()
  },
  methods: {
    //禁止滚动
    stopScrollFun(evt) {
      evt = evt || window.event;
      if(evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble=true;
        evt.returnValue = false;
      }
      return false;
    },
    async getAllDeptList() {
      let list = await this.$httpN.postB('sys/dept/listAll')
      this.departmentList = treeDataTranslate(list, 'id', 'pid')
    },
    getCurMonth() {
      let date = new Date();
      let seperator = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      if (month >= 1 && month <= 9) month = "0" + month;
      this.curMonth = year + seperator + month;
      this.searchData.month = year + seperator + month;
      let lastMonth = date.getMonth();
      if(lastMonth === 0) {
        this.lastMonth = (year - 1) + seperator + '12'
      } else {
        if (lastMonth >= 1 && lastMonth <= 9) lastMonth = "0" + lastMonth;
        this.lastMonth = year + seperator + lastMonth
      }
    },
    handleSizeChange(val) {
      this.pageConfig.pageSize = val;
      this.getAttendanceList(true)
    },
    handleCurrentChange(val) {
      this.pageConfig.pageIndex = val;
      this.getAttendanceList()
    },
    async getAttendanceList(init) {
      if(init) this.pageConfig.pageIndex = 1
      let {list, totalCount} = await this.$httpN.postB('archives/attendance/list', {
        attendanceUserName: this.searchData.name,
        attendanceStatisticsDuration: this.searchData.month,
        page: this.pageConfig.pageIndex,
        limit: this.pageConfig.pageSize,
      })
      this.attendanceList = list
      if(init) this.pageConfig.totalCount = totalCount
    },
    showDialog(item) {
      formUtil.resetData(this.form);
      if(this.$refs.form) this.$refs.form.clearValidate();
      if(item) this.form = JSON.parse(JSON.stringify(item))
      this.dialogVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.form.attendanceStatisticsDuration = this.searchData.month
          this.form.attendanceActual = this.attendanceActual
          if( !await this.$httpN.postB(!this.form.id ? 'archives/attendance/save' : 'archives/attendance/update', this.form)) return
          formUtil.submitSuccess('保存成功');
          this.getAttendanceList();
          this.dialogVisible = false;
        }
      });
    },
    async delAttendance(type) {
      let ids = type ? this.multipleSelection.map(item => item.id) : [this.form.id]
      formUtil.submitConfirm('请问您是否确认删除该记录', async ()=> {
        if(!await this.$httpN.postB('archives/attendance/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.getAttendanceList(true);
        this.dialogVisible = false;
      })
    },
    selectDingUsers(id, name, num){
      let idArr = [];
      idArr.push(this.form[id])
      this.complexPicker(num, [], idArr).then((data)=>{
        this.form[id] = data.map(item => item.emplId).join(',');
        this.form[name] = data.map(item => item.name).join(',');
      })
    },
    async exportList() {
      let fileData = await this.$httpN.get('archives/attendance/export', { attendanceStatisticsDuration: this.searchData.month }, 'blob');
      this.downFile(fileData, this.searchData.month+'考勤汇总.xls');
    },
    downFile(blob, fileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      }
    },
    importList() {
      if(this.searchData.month !== this.lastMonth) return this.$message.error("只可导入上月数据")
      this.$refs.uploadInput.click()
    },
    uploadFile(e) {
      this.loading = true;
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("duration", this.searchData.month);
      formData.append("file", file);
      formData.append("name", 'file');
      this.$httpN.upload('archives/attendance/fileUpload', formData).then((res) => {
        if(res.status === 200 && res.data.code === 0) {
          formUtil.submitSuccess('上传成功')
          this.loading = false;
          this.getAttendanceList(true)
        }else{
          this.$message.error('上传文件出错,请重试')
        }
      })
      e.target.value = '';
    },
    // 菜单树选中
    menuListTreeCurrentChangeHandle (data, node) {
      this.form.attendanceDeptId = data.id
      this.form.attendanceDeptName = data.name
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  }
}
</script>

<style lang='scss' scoped>
.content-wrapper {
  height: 100vh;
  min-width: 500px;
  .nav {
    display: flex;
    height: 50px;
    line-height: 50px;
    padding: 0 20px;
    justify-content: space-between;
    border-bottom: 1px solid #DCDFE6;
    .el-breadcrumb {
      display: flex;
      align-items: center;
      .el-breadcrumb__item {
        float: none;
      }
    }
  }
  .content {
    height: calc(100vh - 50px);
    overflow: auto;
    .search-bar {
      padding: 0 20px;
      height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .main-content {
      padding: 0 20px;
    }
    .page {
      height: 50px;
      display: flex;
      align-items: center;
      flex-direction: row-reverse;
    }
  }
}
</style>